package cn.tedu.usersecurity.controller;

import cn.tedu.usersecurity.ex.ServiceException;
import cn.tedu.usersecurity.mapper.UserMapper;
import cn.tedu.usersecurity.pojo.dto.UserLoginDTO;
import cn.tedu.usersecurity.pojo.dto.UserRegDto;
import cn.tedu.usersecurity.pojo.entity.User;
import cn.tedu.usersecurity.pojo.vo.UserVo;
import cn.tedu.usersecurity.security.AuthenticationUser;
import cn.tedu.usersecurity.web.JsonResult;
import cn.tedu.usersecurity.web.StatusCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    UserMapper mapper;

    @RequestMapping("/login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO){
        System.out.println("userLoginDTO = " + userLoginDTO );
        //创建认证对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUsername(), userLoginDTO.getPassword());
        // 通过认证管理器 执行认证，并获取结果
        Authentication authenticateResult = authenticationManager.authenticate(authentication);

        //代码执行到这里代码并没有抛出用户名不存在或密码错误相关异常, 代表登录成功
        // 将认证结果存入到SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authenticateResult);
        //authenticateResult.getPrincipal()得到的是当前登录的用户信息AuthenticationUser
        System.out.println(authenticateResult.getPrincipal());
        return JsonResult.ok(authenticateResult.getPrincipal());
    }


    @RequestMapping("/reg")
    public JsonResult reg(@RequestBody UserRegDto userRegDto){
        System.out.println("userLoginDTO = " + userRegDto);

        User user = new User();
        BeanUtils.copyProperties(userRegDto,user);

        UserVo userVo = mapper.selectByUserName(user.getUsername()) ;
        if (userVo!=null){
            throw new ServiceException(StatusCode.USER_NAME_EXIST,"用户名已被注册!");
        }
        mapper.insert(user);
        return JsonResult.ok();
    }

    @RequestMapping("/permission")
    @PreAuthorize("hasAuthority('ADMIN')")
    public JsonResult permission(){
        return JsonResult.ok();
    }

    @RequestMapping("/current")//通过以下注解得到当前登录的用户信息
    public JsonResult current(@AuthenticationPrincipal AuthenticationUser user){
        System.out.println("user = " + user);
        return JsonResult.ok(user);//将登录的用户信息响应给客户端
    }


    @RequestMapping("/logout")
    public JsonResult logout(){
        //清除上下文 达到退出登录的目的
        SecurityContextHolder.clearContext();
        return JsonResult.ok();
    }

}
